package com.cn.jx.city.service.Impl;

import com.cn.jx.city.entity.City;
import com.cn.jx.city.service.ICityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.List;
import java.util.regex.Pattern;

@Service("cityService")
public class CityServiceImpl implements ICityService {

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public void saveCity(City city) {
        mongoTemplate.save(city);
    }

    @Override
    public List<City> findCityByType(String parentCode) {
        Query query= Query.query(Criteria.where("parentCode").is(parentCode));
        query.with(new Sort(Sort.Direction.DESC,"sort"));
        return mongoTemplate.find(query,City.class);
    }

    @Override
    public List<City> findCityLikeName(String cityName) {
        String likeName= MessageFormat.format("^.*{0}.*$",cityName);
        Pattern pattern=Pattern.compile(likeName,Pattern.CASE_INSENSITIVE);
        Criteria criteria=new Criteria();
        criteria.orOperator(Criteria.where("allName").regex(pattern),
                Criteria.where("shortName").regex(pattern),
                Criteria.where("aliasName").regex(pattern),
                Criteria.where("englishName").regex(pattern));
        Query query=Query.query(criteria);
        query.with(new Sort(Sort.Direction.DESC,"sort"));
        return mongoTemplate.find(query,City.class);
    }

    @Override
    public City findCityByCode(String code) {
        Query query= Query.query(Criteria.where("code").is(code));
        return mongoTemplate.findOne(query,City.class);
    }
}
